package cn.jhc.servlet;

import cn.jhc.beans.SurveyItem;
import cn.jhc.db.SurveyItemDao;
import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

@WebServlet("/list_by_page.do")
public class PageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        String page = req.getParameter("page");
        int pageNo = 1;
        if (page != null) {
            pageNo = Integer.parseInt(page);
        }
        
        Connection connection = (Connection) req.getServletContext().getAttribute("connection");
        int count = SurveyItemDao.count(connection);
        
        String pageSizeStr = req.getServletContext().getInitParameter("page_size");
        int pageSize = Integer.parseInt(pageSizeStr);
        
        int offset = (pageNo - 1) * pageSize;
        List<SurveyItem> items = SurveyItemDao.findByPage(connection, offset, pageSize);

        Map<String, Object> data = Map.of("items", items, "count", count, "pageNo", pageNo, "pageSize", pageSize);
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        Gson gson = new Gson();
        resp.getWriter().write(gson.toJson(data));
    }
}
